import asyncWx from '../../utils/asyncWx.js';
Page({
  data:{
    address:{},
    cart:[],
    isAllSelected:false,
    totalPrice:0,
    totalSelectedGoodsNum:0
  },
  onLoad:function(options) {
  },
  onShow() {
    const address = wx.getStorageSync('address');
    this.setData({address});
    const cart = wx.getStorageSync('cart') || [];
    this.updateCartData(cart);
  },
  onTapChooseAddress() {
  },
  onChangeSelectItem(ev) {
    const goodsId = ev.currentTarget.dataset.id;
    let cart = this.data.cart;
    let index = cart.findIndex(val => val['goods_id'] === goodsId);
    cart[index]['is_cart_selected'] = !cart[index]['is_cart_selected'];
    this.updateCartData(cart);
  },
  onChangeSelectAll() {
    let {cart, isAllSelected} = this.data;
    isAllSelected = !isAllSelected;
    cart.forEach((val, i, self) => {
      val['is_cart_selected'] = isAllSelected;
    });
    this.updateCartData(cart);
  },
  async onTapItemNumEdit(ev) {
    const {id, opera} = ev.currentTarget.dataset;
    let {cart} = this.data;
    const index = cart.findIndex(val => val['goods_id'] === id);
    if (opera === 1 || opera === -1 && cart[index]['in_cart_number'] > 1) {
      cart[index]['in_cart_number'] += opera;
      this.updateCartData(cart);
    } else {
      const userConfirm = await asyncWx.showModal({content:'您是否要删除？'});
      if (userConfirm.confirm) {
        cart.splice(index, 1);
        this.updateCartData(cart);
      } else if (userConfirm.cancel) {
      }
    }
  },
  onTapPay() {
    const {address, totalSelectedGoodsNum} = this.data;
    if (totalSelectedGoodsNum === 0) {
      wx.showToast({title:'您还没有选购商品', icon:'none', mask:true});
      return;
    }
    wx.navigateTo({url:'/pages/pay/pay'});
  },
  updateCartData(cart) {
    let isAllSelected = true;
    let totalPrice = 0, totalSelectedGoodsNum = 0;
    cart.forEach((val, i, self) => {
      if (val['is_cart_selected']) {
        totalPrice += val['in_cart_number'] * val['goods_price'];
        totalSelectedGoodsNum++;
      } else {
        isAllSelected = false;
      }
    });
    if (cart.length === 0) {
      isAllSelected = false;
    }
    this.setData({cart, isAllSelected, totalPrice, totalSelectedGoodsNum});
    wx.setStorageSync('cart', cart);
  }
});